package com.bike.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bike.dto.TreeDto;
import com.bike.entity.SysMenu;
import com.bike.entity.SysRole;
import com.bike.entity.SysUser;
import com.bike.mapper.SysMenuMapper;
import com.bike.mapper.SysRoleMapper;
import com.bike.mapper.SysUserMapper;
import com.bike.util.Md5Util;
import com.bike.util.PageData;
import com.bike.util.RightsHelper;
import com.bike.util.TimeManager;
import com.bike.util.TransFerUtil;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
@Service
public class SystemServiceImpl extends BaseServcieImpl  {
	
	@Autowired
	SysUserMapper userMapper;
	@Autowired
	SysMenuMapper menuMapper;
	@Autowired
	SysRoleMapper roleMapper;
	
	public List<SysMenu> selectMenuByParentId( long parentId) {
		List<SysMenu> menuList=menuMapper.selectByParentId(parentId);
		return menuList;
	}
	public List<SysMenu> selectMenuByParentId(String menuRights, long parentId) {
		List<SysMenu> menuList=menuMapper.selectByParentId(parentId);
		
		if(parentId==0){
			List<SysMenu> all=menuMapper.selectAll(new PageData());
			List<SysMenu> filterMenuList=RightsHelper.filterMenu(menuRights,all);
			Set<Long> parentIdSet=new HashSet<>();
			for(SysMenu menu:filterMenuList){
				parentIdSet.add(menu.getParentId());
			}
			List<SysMenu> menuListNew=new ArrayList<>();
			for(long item:parentIdSet){
				for(SysMenu menu:menuList){
					if(menu.getMenuId().equals(item)){
						menuListNew.add(menu);
						break;
					}
				}
			}
			return menuListNew;
		}
		
		return RightsHelper.filterMenu(menuRights,menuList);
	}

	public int deleteMenu(long menuId) {
		 return menuMapper.deleteByPrimaryKey(menuId);
	}

	public PageData selectSysUserList(PageData pd) {
		PageData result=new PageData();
		PageBounds pageBounds=(PageBounds) pd.get("pageB");
		String advanceFilter=pd.getString("advanceFilter");
		if(advanceFilter!=null&&!advanceFilter.equals("")){
			advanceFilter=advanceFilter.replaceAll("'", "");
			JSONArray array=JSONObject.parseArray(advanceFilter);
			StringBuffer buffer=new StringBuffer();
			for(int i=0;i<array.size();i++){
				JSONObject object=array.getJSONObject(i);
				String field=object.getString("field");
				String op=object.getString("op");//equal  contains  notequal  greater  greaterorequal  less  lessorequal  beginwith  endwith
				String value=object.getString("value");
				buffer.append(" and ").append(TransFerUtil.getMybatisField(field)).append(TransFerUtil.getMybatisOperation(op,value));
			}
			if(array.size()>0){
				pd.put("condition", buffer.toString());
			}
		}
		List<SysUser> records= userMapper.selectByPage(pd,pageBounds);
		result.put("rows",records );
		result.put("total", ((PageList<SysUser>) records).getPaginator().getTotalCount());
		return result;
	}

	public SysUser selectBySysUserId(Long userId) {
		SysUser user=userMapper.selectByPrimaryKey(userId);
		
		List<TreeDto> roleList=roleMapper.selectTreeDtoAll(new PageData());
		user.setRole(JSONArray.toJSONString(roleList));
		return user;
	}

	public void saveOrUpdate(PageData pd, SysUser record) {
		if(StringUtils.isNotEmpty(record.getPwd())){
			record.setPwd(Md5Util.MD5(record.getPwd()));
		}else{
			record.setPwd(null);
		}
		long roleId=pd.getLong("roleId");
		if(roleId>0){
			SysRole role=roleMapper.selectByPrimaryKey(roleId);
			record.setRole(role.getName());
			record.setRoleId(roleId);
		}
		
		if(pd.getInteger("userId")>0){
			 //编辑
			userMapper.updateByPrimaryKeySelective(record);
		}else{
			record.setAddTime(TimeManager.currentTime());
			if(pd.getLong("agentId")>0){
				SysRole role=roleMapper.selectByName("代理商");
				record.setRoleId(role.getRoleId());
				record.setRole("代理商");
			}
			if(!pd.getString("businessId").equals("")){
				SysRole role=roleMapper.selectByName("商家管理员");
				record.setRoleId(role.getRoleId());
				record.setRole("商家管理员");
			}
			
			userMapper.insertSelective(record);
		}
	}

	public void deleteSysUser(long userId) {
		userMapper.deleteByPrimaryKey(userId);
	}

	public List<TreeDto>  selectTreeDtoRole() {
		List<TreeDto> roleList=roleMapper.selectTreeDtoAll(new PageData());
		return  roleList ;
	}

	public SysUser selectByUserName(String userName) {
		return userMapper.selectByUserName(userName);
	}

	public SysRole selectRoleById(Long roleId) {
		return roleMapper.selectByPrimaryKey(roleId);
	}

	public int updateUser(SysUser admin) {
		return userMapper.updateByPrimaryKeySelective(admin);
	}

	public boolean isRight(HttpServletRequest request) {
		String url=request.getRequestURI();
		SysRole role=(SysRole) request.getSession().getAttribute("role");
		if(role!=null){
			SysMenu menu=menuMapper.selectByUrl(url);
			if(menu!=null){
				if(RightsHelper.testRights(role.getMenuRights(), menu.getMenuId().intValue())){
					return true;
				}
			}
		}
		
		return false;
	}
	public List<SysUser> selectBySysUser(PageData pd) {
		 
		return userMapper.selectByPage(pd, (PageBounds)pd.get("pageB"));
	}

}
